package com.erytech.linktalk.web.server;

import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.opengoss.core.IPluginContext;
import org.opengoss.web.core.IWebPlugin;

import com.erytech.linktalk.dao.DaoFacade;
import com.erytech.linktalk.dao.domain.Message;
import com.erytech.linktalk.dao.domain.User;
import com.erytech.linktalk.service.ServiceFacade;
import com.erytech.linktalk.web.client.service.MessageInfo;
import com.erytech.linktalk.web.client.service.UserInfo;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class BaseServlet extends RemoteServiceServlet {

	private DaoFacade daoFacade = null;
	
	private ServiceFacade serviceFacade = null;

	@Override
	public void init() throws ServletException {
		super.init();
		IWebPlugin webPlugin = (IWebPlugin) getServletContext().getAttribute("WebPlugin");
		IPluginContext pluginContext = webPlugin.getContext();
		daoFacade = (DaoFacade)pluginContext.getServiceRegistry().getService("LinkTalkDao:DaoFacade");
		serviceFacade  = (ServiceFacade)pluginContext.getServiceRegistry().getService("LinkTalkService:ServiceFacade");
	}

	protected HttpSession getSession() {
		return getThreadLocalRequest().getSession(true);
	}

	protected ServiceFacade getServiceFacade() {
		if (serviceFacade == null) {
			throw new IllegalStateException("No ServiceFacade Found!");
		}
		return serviceFacade;
	}

	protected DaoFacade getDaoFacade() {
		if (daoFacade == null) {
			throw new IllegalStateException("No DaoFacade Found!");
		}
		return daoFacade;
	}

	protected Message toMessage(MessageInfo messageInfo) {
		Message message = new Message();
		message.setRoomId(messageInfo.getRoomId());
		message.setBody(messageInfo.getBody());
		message.setFrom(messageInfo.getFrom());
		message.setRoomId(messageInfo.getRoomId());
		String to = messageInfo.getTo();
		if(to == null || to.length() == 0) {
			to = (User.ALL);
		}
		message.setTo(to);
		return message;
	}

	protected MessageInfo toMessageInfo(Message message) {
		MessageInfo messageInfo = new MessageInfo();
		messageInfo.setBody(message.getBody());
		messageInfo.setFrom(message.getFrom());
		messageInfo.setPostTime(new Date(message.getPostTime().getTime()));
		messageInfo.setTo(message.getTo());
		return messageInfo;
	}

	protected User toUser(UserInfo userInfo) {
		User user = new User();
		user.setDescription(userInfo.getDescription());
		user.setImage(userInfo.getImage());
		user.setName(userInfo.getName());
		user.setRoomId(userInfo.getRoomId());
		user.setSex(userInfo.getSex());
		user.setId(User.createId(userInfo.getName(), userInfo.getRoomId()));
		return user;
	}

	protected UserInfo toUserInfo(User user) {
		UserInfo userInfo = new UserInfo();
		userInfo.setDescription(user.getDescription());
		userInfo.setImage(user.getImage());
		userInfo.setName(user.getName());
		userInfo.setRoomId(user.getRoomId());
		userInfo.setSex(user.getSex());
		return userInfo;
	}

}